package com.yywq.controller;

import com.yywq.error.BusinessException;
import com.yywq.error.EnumBusinessError;
import com.yywq.mapper.UserMapper;
import com.yywq.pojo.User;
import com.yywq.response.CommonReturnType;
import com.yywq.utils.RedisUtil;
import com.yywq.utils.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: 吴磊
 * @program: yywq
 * @create: 2021-03-18 18:46
 */

@RestController
public class SendSmsController {
    @Autowired
    private SendSms sendSms;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 发送短信的接口
     *
     * @param telPhone
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/getotp", method = RequestMethod.POST)
    private CommonReturnType getOtp(@RequestParam("telPhone") String telPhone) throws BusinessException {
        //先验证手机号是否存在
        User user = userMapper.getUserByTelPhone(telPhone);
        if (user != null) {
            throw new BusinessException(EnumBusinessError.USER_IS_EXIST);
        }

        try {
            //单纯的就是为了测试能不能连接redis
            redisUtil.hasKey("test");
        } catch (Exception e) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "短信发送失败");
        }

        //发送短信
        if (!redisUtil.hasKey(telPhone)) {
            //生成验证码，并 存储到redis中
            String code = UUID.randomUUID().toString().substring(0, 5);
            HashMap<String, Object> map = new HashMap();
            map.put("code", code);
            boolean isSend = sendSms.sendSms(telPhone, map);
            if (isSend) {
                //将该用户的验证码加入到redis并设置有效时间为5分钟
//                redisTemplate.opsForValue().set(telPhone, code);
                redisTemplate.opsForValue().set(telPhone, code, 5, TimeUnit.MINUTES);
            }
        } else {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "请务重复发送");
        }
        return CommonReturnType.create(null);
    }

}
